package fun.wxy.camera.fragment;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import fun.wxy.camera.R;
import fun.wxy.camera.entity.UsbDeviceAdapter;
import fun.wxy.camera.entity.UsbDeviceItem;

/**
 * USB设备列表
 */
public class UsbDevicesFragment extends Fragment {

    private UsbManager usbManager;
    private UsbDeviceAdapter adapter;
    private static final int USB_PERMISSION_REQUEST_CODE = 1001;
    private static final String ACTION_USB_PERMISSION = "fun.wxy.camera.USB_PERMISSION";

    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                handlePermissionResponse(intent);
            } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                updateDeviceList();
                showToast("检测到新设备接入");
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                updateDeviceList();
                showToast("设备已断开连接");
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_usb_devices, container, false);

        // 绑定返回按钮
        ImageView backImg = rootView.findViewById(R.id.btn_back);
        backImg.setOnClickListener(v -> {
            requireActivity().getSupportFragmentManager().popBackStack();
        });

        return rootView;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        usbManager = (UsbManager) requireContext().getSystemService(Context.USB_SERVICE);

        RecyclerView recyclerView = view.findViewById(R.id.usb_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new UsbDeviceAdapter(usbManager, new ArrayList<>());
        recyclerView.setAdapter(adapter);

        setupClickListener();
        updateDeviceList();
    }

    @Override
    public void onResume() {
        super.onResume();
        registerUsbReceivers();
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterUsbReceivers();
    }

    private void registerUsbReceivers() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        filter.addAction(ACTION_USB_PERMISSION);
        requireContext().registerReceiver(usbReceiver, filter);
    }

    private void unregisterUsbReceivers() {
        requireContext().unregisterReceiver(usbReceiver);
    }

    private void setupClickListener() {
        adapter.setOnItemClickListener(position -> {
            UsbDeviceItem item = adapter.getItem(position);
            if (item != null) {
                requestUsbPermission(item.getDevice());
            }
        });
    }

    private void updateDeviceList() {
        Map<String, UsbDevice> deviceMap = usbManager.getDeviceList();
        List<UsbDeviceItem> items = new ArrayList<>();

        for (UsbDevice device : deviceMap.values()) {
            items.add(new UsbDeviceItem(
                    device,
                    device.getDeviceName(),
                    device.getVendorId(),
                    device.getProductId()
            ));
        }

        adapter.updateList(items);
    }

    private void requestUsbPermission(@Nullable UsbDevice device) {
        if (device == null) {
            showToast("设备不存在");
            return;
        }

        if (usbManager.hasPermission(device)) {
            showToast("已拥有该设备权限");
            return;
        }

        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            flags |= PendingIntent.FLAG_MUTABLE;
        }

        PendingIntent permissionIntent = PendingIntent.getBroadcast(
                requireContext(),
                USB_PERMISSION_REQUEST_CODE,
                new Intent(ACTION_USB_PERMISSION),
                flags
        );

        usbManager.requestPermission(device, permissionIntent);
        showToast("正在请求设备权限...");
    }

    private void handlePermissionResponse(Intent intent) {
        UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        boolean granted = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false);

        if (device == null) return;

        if (granted) {
            showToast("已获得权限: " + device.getDeviceName());
            updateDeviceList();
        } else {
            showToast("权限被拒绝: " + device.getDeviceName());
        }
    }

    private void showToast(String message) {
        Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
    }
}